using System.Data;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Xml;

namespace Coffee.SurveyControls.SurveyQuestions
{
    public class ISQConfiguration
    {
        XmlNode configuration;

        private string id = null;
        private string type = null;
        private ISQEvent _event = null;

        public string Id { get { return id; } }
        public string Type { get { return type; } }
        public ISQEvent Event { get { return _event; } }

        public ISQConfiguration(XmlNode configuration)
        {
            this.configuration = configuration;
            this.id = configuration.Attributes["id"].Value;
            this.type = configuration.Attributes["type"].Value;
            XmlNode xEvent;
            if ((xEvent = configuration.SelectSingleNode("event")) != null)
            {
                _event = new ISQEvent(xEvent);
            }
        }
    }

    public class ISQEvent
    {
        string target;
        string script;
        string param;

        public string Target { get { return target; } }
        public string Script { get { return script; } }
        public string Parameters { get { return param; } }

        public ISQEvent(XmlNode configuration)
        {
            // Need to improve event handling semantics
            if (configuration != null)
            {
                XmlNode xScript = configuration.SelectSingleNode("script");
                XmlNode xTarget = configuration.SelectSingleNode("target");
                XmlNode xParam = configuration.SelectSingleNode("param");

                script = xScript.SelectSingleNode("text()").Value;
                target = xTarget.SelectSingleNode("text()").Value;
                param = xParam.SelectSingleNode("text()").Value;
            }
        }
    }

    /// <summary>
    /// Summary description for ISurveyQuestionControl
    /// </summary>
    public abstract class SurveyQuestionRow : HtmlTableRow
    {
        protected XmlNode rootNode;
        protected string ctlType;
        //ISQCtlInitEventArgs inittargs;
        protected ISQConfiguration config;

        protected HtmlTableCell quesCell;
        protected HtmlTableCell prevCell;
        protected HtmlTableCell currCell;

        //protected Control question;
        protected Control previousAnswerControl;
        protected Control currentAnswerControl;
        protected Control questionControl;

        protected string ctlId;
        protected bool locked;
        protected bool hasClientCallback;
        protected bool isDynamic;

        public bool Locked { get { return locked; } set { locked = value; } }
        public bool HasClientCallback { get { return hasClientCallback; } set { hasClientCallback = value; } }
        public bool IsDynamic { get { return isDynamic; } set { isDynamic = value; } }
        public bool IsDirty { get { return CheckIsDirty(); } }

        public Control QuestionControl { get { return questionControl; } }
        public Control PreviousControl { get { return previousAnswerControl; } }
        public Control CurrentControl { get { return currentAnswerControl; } }

        public XmlNode Configuration { get { return rootNode; } }

        SurveyControl parent;
        public SurveyQuestionRow(SurveyControl parent, XmlNode configuration)
        {
            this.parent = parent;
            quesCell = new HtmlTableCell();
            prevCell = new HtmlTableCell();
            currCell = new HtmlTableCell();
            this.rootNode = configuration;
            config = new ISQConfiguration(configuration);
            Cells.Add(quesCell);
            Cells.Add(prevCell);
            Cells.Add(currCell);
            this.ctlId = configuration.Attributes["id"].Value;
            this.ctlType = configuration.Attributes["type"].Value;

            if (configuration.Attributes["dynamic"] != null)
                this.isDynamic = true;

            quesCell.Controls.Add(CreateQuestionControl());
            Initialize();

            previousAnswerControl = CreatePreviousDataControl();
            currentAnswerControl = CreateCurrentDataControl();

            prevCell.Controls.Add(previousAnswerControl);
            currCell.Controls.Add(currentAnswerControl);
        }

        public SurveyQuestionRow(XmlNode configuration)
        {
            //this.parent = null;
            //quesCell = new HtmlTableCell();
            //prevCell = new HtmlTableCell();
            //currCell = new HtmlTableCell();
            //this.rootNode = configuration;
            //currCell.Controls.Add(new TextBox());
            //this.ctlId = configuration.Attributes["id"].Value;
            //this.ctlType = configuration.Attributes["type"].Value;

            //Initialize();
        }

        public new SurveyControl Parent
        {
            get
            {
                return parent;
            }
        }

        public virtual bool Validate()
        {
            return true;
        }

        protected virtual bool CheckIsDirty()
        {
            return true;
        }


        protected override void CreateChildControls()
        {


        }

        protected virtual void Initialize()
        {
        }

        public virtual void LoadDynamicData()
        {
        }

        public virtual void LoadData()
        {
        }

        public virtual void SaveData()
        {
        }

        // Always called during a page load
        public virtual void SetupCallBackHandlers()
        {
        }

        // Only called when controls are rendered
        public virtual void SetupClientEventHandlers(Page page)
        {
            //SQObject obj = new SQObject(configuration);
            //XmlNode xEvent = configuration.SelectSingleNode("event[@type='onchange']");
            //if (xEvent != null)
            //{
            //    string target = xEvent.SelectSingleNode("target/text()").Value;
            //    EventHandler handler = null;
            //    handler = delegate(object sender, EventArgs e)
            //    {
            //        if (page.Request.Form["__EVENTTARGET"] == currentYearData.UniqueID)
            //        {
            //            ISurveyQuestionControl ctl = (ISurveyQuestionControl)Coffee.FindControl(target);
            //            XmlNode config = configuration.SelectSingleNode("ancestor::tab//*[@id='" + target + "']");
            //            if ((config != null) && (ctl != null))
            //            {
            //                // call Reload on the control
            //                ctl.Reload();
            //            }
            //            else
            //            {
            //                throw new Exception(string.Format("Could not find the target control '{0}' for the parent control '{1}'", target, obj.ID));
            //            }
            //            page.Load -= handler;
            //        }
            //    };

            //    // 
            //    if (typeof(ListControl).IsAssignableFrom(currentYearData.GetType()))
            //    {
            //        ((ListControl)currentYearData).AutoPostBack = true;
            //    }

            //    //src.AutoPostBack = true;
            //    page.Load += handler;
            //}
        }

        DataSet dsQuestions;

        protected virtual Control CreateQuestionControl()
        {
            //dsQuestions = Parent.Questions;

            string text = string.Empty;

            //string questionId = string.Empty;

            //if (rootNode.Attributes["questionid"] != null)
            //{
            //    questionId = rootNode.Attributes["questionid"].Value;
            //}

            if (rootNode.SelectSingleNode("text") != null)
            {
                text = (string)Coffee.Parser.ParseValue(rootNode.SelectSingleNode("text"));
            }
            //DataRow[] dra = null;

            //if (dsQuestions != null && questionId != string.Empty)
            //{
            //    dra = dsQuestions.Tables[0].Select("QuestionID=" + questionId);
            //    if (dra.Length > 0)
            //    {
            //        text = dra[0]["QuestionDescription"].ToString();
            //    }
            //}

            Control ctl;
            Label l = new Label();
            l.CssClass = "question";
            l.Text = text;

            ctl = l;

            //quesCell.VAlign = "top";

            string ctlId = rootNode.Attributes["id"].Value;
            parent.SurveyControls.Add(ctlId + "-ques", ctl);

            //// Display any image tooltips
            //XmlNode toolTip = null;
            //string hint = string.Empty;
            //bool hasHint = false;

            //if (dra != null && dra.Length > 0)
            //{
            //    hasHint = true;
            //    hint = dra[0]["Hint"].ToString();
            //}
            //else if ((toolTip = rootNode.SelectSingleNode("tooltip/text()")) != null)
            //{
            //    hasHint = true;
            //    hint = toolTip.Value;
            //}

            //if ((rootNode.Attributes["tooltip"] != null) && (rootNode.Attributes["tooltip"].Value == "true"))
            //{
            //    if (hasHint)
            //    {
            //        Image img = new Image();
            //        img.ToolTip = hint;
            //        img.AlternateText = hint;
            //        img.ImageAlign = ImageAlign.Right;
            //        img.ImageUrl = "../images/help-white.gif";
            //        quesCell.Controls.Add(img);
            //    }
            //}

            return ctl;
        }

        protected abstract Control CreateCurrentDataControl();

        protected abstract Control CreatePreviousDataControl();


    }
}